﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using KPIS.GERP.GFMS.DAL;
using KPIS.GERP.GFMS.IBLL;
using KPIS.GERP.GFMS.BLL;
using KPIS.GERP.GFMS.MODEL;
using Telerik.Web.UI;
using _WebShared.Classes;
using KPIS.DBM;
using System.Security.AccessControl;
using System.IO;

namespace KPIS.GERP.GFMS.APP.App_UI.Commons
{
    public class Main : System.Web.UI.Page
    {
        D_SECURITY_Users user = new D_SECURITY_Users();

        public DataTable ExecuteQuery(string strSQL)
        {
            DBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);
            DataTable dtb;

            try
            {
                dbManager.Open();
                dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dbManager.Dispose();
            }

            return dtb;
        }

        public string WebString(string String)
        {
            string strResult = "";

            strResult = String.Replace("&nbsp;", "");

            return strResult;
        }

        public M_FIM_SystemControls GetSystemControls()
        {
            if (Session["SCInfo"] == null)
            {
                IBLL_FIM_SystemControls sc = new B_FIM_SystemControls();
                Session["SCInfo"] = sc.GetInfo();
            }
            return (M_FIM_SystemControls)Session["SCInfo"];
        }

        public string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่พบข้อมูล";

            return String.Format("ลำดับที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b>", offset, total);
        }

        public void SetupReport(string strReportName, string strSeq)
        {
            Session["ReportName"] = strReportName;
            Session["ReportSeq"] = strSeq;
        }

        public void InsertEmptyDDLSelect(RadComboBox ddl)
        {
            RadComboBoxItem empty = new RadComboBoxItem("<เลือกรายการ>", "");
            ddl.Items.Insert(0, empty);
        }

        public void InsertEmptyDDLAll(RadComboBox ddl)
        {
            RadComboBoxItem empty = new RadComboBoxItem("<ทั้งหมด>", "");
            ddl.Items.Insert(0, empty);
        }

        public void ClearDDL(RadComboBox ddl)
        {
            ddl.ClearSelection();
            ddl.Items.Clear();

            RadComboBoxItem empty = new RadComboBoxItem("<ทั้งหมด>", "");
            ddl.Items.Insert(0, empty);
            ddl.SelectedIndex = 0;
        }

        public string ErrorEmpty(string strFieldName)
        {
            return "กรุณากรอกข้อมูล [" + strFieldName + "]";
        }

        public void MessageAlert(Page p, string strMessage)
        {
            ScriptManager.RegisterClientScriptBlock(p, p.GetType(), "onclick"
                , "window.alert('" + strMessage + "');", true);
        }

        public void MessageAlert2(Page p, string strMessage)
        {
            // Only page that had RadAjaxManager
            RadAjaxManager manager = RadAjaxManager.GetCurrent(p);
            manager.Alert(strMessage);
        }

        public string ConvertNumberToString(Object o)
        {
            string result = "";

            if (o == null)
            {
                result = "0.00";
            }
            else
            {
                switch (o.GetType().ToString())
                {
                    case "System.int" :
                    case "System.Int32" :
                        result = Convert.ToInt32(o).ToString("#,###.##");
                        break;
                    case "System.double" :
                    case "System.Double" :
                        result = Convert.ToDouble(o).ToString("#,###.##");
                        break;
                }
            }

            return result;
        }
        
        public enum EditMode
        {
            AddNew,
            Edit,
            View,
            Info, 
            ShowGrid
        }


        public Nullable<int> ConvertNullInt(Object o)
        {
            Nullable<int> result = (o == null ? null : (o.ToString().Length == 0 ? null : (Nullable<int>)Convert.ToInt32(o)));
            return result;
        }

        public Nullable<double> ConvertNullDouble(Object o)
        {
            Nullable<double> result = (o == null ? null : (o.ToString().Length == 0 ? null : (Nullable<double>)Convert.ToDouble(o)));
            return result;
        }

        public Nullable<DateTime> ConvertNullDateTime(Object o)
        {
            Nullable<DateTime> result = (o == null ? null : (o.ToString().Length == 0 ? null : (Nullable<DateTime>)Convert.ToDateTime(o)));
            return result;
        }

        public Nullable<TimeSpan> ConvertNullTimeSpan(Object o)
        {
            Nullable<TimeSpan> result = (o == null ? null : (o.ToString().Length == 0 ? null : (Nullable<TimeSpan>)Convert.ToDateTime(o).TimeOfDay));
            return result;
        }

        public Nullable<decimal> ConvertNullDecimal(Object o)
        {
            Nullable<decimal> result = (o == null ? null : (o.ToString().Length == 0 ? null : (Nullable<decimal>)Convert.ToDecimal(o)));
            return result;
        }

        public object ConvertToDB(Object o)
        {
            return (o == null || o.ToString().Trim().Length == 0 ? DBNull.Value : o);
        }

        //public UserInfo GetUserInfo(string strUserID)
        //{
        //    UserInfo userinfo = new UserInfo();
        //    DataTable dtb = user.GetUserInfo(strUserID);

        //    if (dtb.Rows.Count > 0)
        //    {
        //        userinfo.UserName = dtb.Rows[0]["user_name"].ToString();
        //        userinfo.EmpSeq = dtb.Rows[0]["emp_seq"].ToString();
        //    }

        //    return userinfo;
        //}

        public int GetBgmMonth(string strBgmSourceSeq, Nullable<DateTime> dt)
        {
            int nBgmMonth;
            int nMonthStart;
            int nCurrentMonth;

            IBLL_BGM_MAS_Source source = new B_BGM_MAS_Source();
            M_BGM_MAS_Source info = source.GetInfo(strBgmSourceSeq);
            nMonthStart = info.month_start.Value;

            if (dt == null)
            {
                dt = DateTime.Today;
            }

            nCurrentMonth = dt.Value.Month;
            nBgmMonth = (nMonthStart <= nCurrentMonth ? nCurrentMonth - nMonthStart + 1 : nCurrentMonth + 13 - nMonthStart);

            return nBgmMonth;
        }

        public void UpdateTabStrip(RadTabStrip tab, int nSelectIndex, string strMode)
        {
            if (strMode == "AddNew")
            {
                for (int i = 0; i < tab.Tabs.Count; i++)
                {
                    tab.Tabs[i].Enabled = i <= nSelectIndex;
                }
            }
            else
            {
                for (int i = 0; i < tab.Tabs.Count; i++)
                {
                    tab.Tabs[i].Enabled = true;
                }
            }
        }

        public void FindTreeValue(RadTreeView treeView, string strValue)
        {
            RadTreeNodeCollection nodes = treeView.Nodes;

            foreach (RadTreeNode tn in nodes)
            {
                if (strValue.Length > 0)
                {
                    if (tn.Value == strValue)
                    {
                        tn.Selected = true;

                        if (tn.ParentNode != null)
                            tn.ParentNode.Expanded = true;

                        return;
                    }
                    FindRecursive(tn, strValue);
                }
            }
        }

        //public void FindTreeValueBgPlan(RadTreeView treeView, string strValue, string strCatagory
        //    , string strBgSourceSeq, string strBgYear, string strBgMonth)
        //{
        //    RadTreeNodeCollection nodes = treeView.Nodes;

        //    foreach (RadTreeNode tn in nodes)
        //    {
        //        if (strValue.Length > 0)
        //        {
        //            if (tn.Value == strValue && tn.Category == strCatagory)
        //            {
        //                tn.Selected = true;
        //                tn.ParentNode.Expanded = true;
        //                return;
        //            }

        //            if (tn.ExpandMode == TreeNodeExpandMode.ServerSideCallBack && tn.Nodes.Count == 0)
        //            {
        //                PopulatePlanNodeOnDemand(tn, TreeNodeExpandMode.ServerSideCallBack
        //                    , strBgSourceSeq, strBgYear, strBgMonth);

        //                tn.Toggle();
        //            }

        //            FindRecursiveBgPlan(tn, strValue, strCatagory
        //                , strBgSourceSeq, strBgYear, strBgMonth);
        //        }
        //    }
        //}

        protected void FindRecursive(RadTreeNode treeNode, string strValue)
        {
            foreach (RadTreeNode tn in treeNode.Nodes)
            {
                if (tn.Value == strValue)
                {
                    tn.Selected = true;

                    if (tn.ParentNode != null)
                        tn.ParentNode.Expanded = true;

                    return;
                }
                FindRecursive(tn, strValue);
            }
        }

        public void FolderACL(String accountName, String folderPath)
        {
            FileSystemRights Rights;

            //What rights are we setting?
            Rights = FileSystemRights.FullControl;
            bool modified;
            InheritanceFlags none = new InheritanceFlags();
            none = InheritanceFlags.None;

            //set on dir itself
            FileSystemAccessRule accessRule = new FileSystemAccessRule(accountName, Rights, none, PropagationFlags.NoPropagateInherit, AccessControlType.Allow);
            DirectoryInfo dInfo = new DirectoryInfo(folderPath);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();
            dSecurity.ModifyAccessRule(AccessControlModification.Set, accessRule, out modified);

            //Always allow objects to inherit on a directory 
            InheritanceFlags iFlags = new InheritanceFlags();
            iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

            //Add Access rule for the inheritance
            FileSystemAccessRule accessRule2 = new FileSystemAccessRule(accountName, Rights, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow);
            dSecurity.ModifyAccessRule(AccessControlModification.Add, accessRule2, out modified);

            dInfo.SetAccessControl(dSecurity);
        }

        //public void NextFocus(Page p, Control ctrl)
        //{
        //    NextFocus(p, ctrl, 500);
        //}

        //public void NextFocus(Page p, Control ctrl, int nScrollVertical)
        //{
        //    if (ctrl == null)
        //        return;

        //    ClientScript.RegisterStartupScript(p.GetType(), "FocusScript"
        //        , "<script language='javascript'>\n"
        //        + "document.getElementById('" + ctrl.ClientID + "').focus();\n"
        //        + "window.scrollBy(0, " + nScrollVertical.ToString() + ");\n"
        //        + "</script>\n"
        //        );
        //}

        //protected void FindRecursiveBgPlan(RadTreeNode treeNode, string strValue, string strCatagory
        //    , string strBgSourceSeq, string strBgYear, string strBgMonth)
        //{
        //    foreach (RadTreeNode tn in treeNode.Nodes)
        //    {
        //        if (tn.Value == strValue && tn.Category == strCatagory)
        //        {
        //            tn.Selected = true;
        //            tn.ParentNode.Expanded = true;
        //            return;
        //        }

        //        if (tn.ExpandMode == TreeNodeExpandMode.ServerSideCallBack && tn.Nodes.Count == 0)
        //        {
        //            PopulatePlanNodeOnDemand(tn, TreeNodeExpandMode.ServerSideCallBack
        //                , strBgSourceSeq, strBgYear, strBgMonth);

        //            tn.
        //            tn.Toggle();
        //        }
        //        FindRecursiveBgPlan(tn, strValue, strCatagory, strBgSourceSeq, strBgYear, strBgMonth);
        //    }
        //}

        //==========================================================================================
        //private void PopulatePlanNodeOnDemand(RadTreeNode ParentNode, TreeNodeExpandMode expandMode
        //    , string strBgSourceSeq, string strBgYear, string strBgMonth)
        //{
        //    IBLL_BGM_StrategyDataMapping strmap = new B_BGM_StrategyDataMapping();
        //    //IBLL_BGM_Plan plan = new B_BGM_Plan();

        //    switch (ParentNode.Category)
        //    {
        //        case "Strat":
        //            IList<M_BGM_StrategyDataMapping> StrInfolist1 = strmap.GetList(ParentNode.Value);
        //            foreach (M_BGM_StrategyDataMapping info in StrInfolist1)
        //            {
        //                RadTreeNode node = new RadTreeNode();
        //                node.Text = info.m_bgm_strategydatalist.bgm_strat_list_name;

        //                node.ExpandMode = expandMode;
        //                if (info.lower_bgm_strat_data_map_seq == null)
        //                {
        //                    node.Category = "LastStrat";
        //                    node.Value = info.bgm_strat_list_seq.ToString();
        //                }
        //                else
        //                {
        //                    node.Category = "Strat";
        //                    node.Value = info.bgm_strat_data_map_seq.ToString();
        //                }
        //                ParentNode.Nodes.Add(node);
        //            }
        //            break;
        //        case "LastStrat":
        //            IList<M_BGM_Plan> planInfolist = plan.GetFull(strBgSourceSeq
        //                , strBgYear, strBgMonth, Session["UserInternalJobsiteSeq"].ToString()
        //                , ParentNode.Value, null);

        //            foreach (M_BGM_Plan info in planInfolist)
        //            {
        //                RadTreeNode node = new RadTreeNode();
        //                node.Text = info.bgm_plan_name + " " + info.amount_remain.ToString();
        //                //UserControl uc = (UserControl)LoadControl((Server.MapPath("../UserControls/FIM_BgmPlan.ascx")));
        //                ////UserControl uc = (UserControl)LoadControl(Server.MapPath("FIM_BgmPlan.ascx"));
        //                //uc.ID = "FIM_BgmPlan1";
        //                //UserControls.FIM_BgmPlan BgmPlan = (UserControls.FIM_BgmPlan)uc;
        //                //BgmPlan.LoadBgmPlan(info.bgm_plan_seq.ToString(), strBgMonth);
        //                node.Value = info.bgm_plan_seq.ToString();
        //                node.Category = "Plan";
        //                //node.Controls.Add(uc);
        //                ParentNode.Nodes.Add(node);
        //            }

        //            ParentNode.Expanded = true;
        //            break;
        //    }
        //}
        //==========================================================================================

        private bool IsAValidNumber(string strNumberText)
        {
            // There can be only one point and the others must be 0-9
            int i;
            int nPointCount = 0;
            string strChar;
            bool bOK = true;

            for (i = 0; i < strNumberText.Length; i++)
            {
                strChar = strNumberText.Substring(i, 1);

                if (strChar == ".")
                    nPointCount++;

                if (nPointCount > 1 || strChar != "." && (int.Parse(strChar) < 0 || int.Parse(strChar) > 9))
                {
                    bOK = false;
                    break;
                }
            }

            return bOK;
        }

        private string EachNumberPositionThaiText(string strReverseNumberText, int nMaxPosition
            , int nCurrentPosition, string[] astrPositionName, string[] astrDigitName)
        {
            int nDigit;
            string strDigitName;
            int nPosition;
            string strPositionName;
            int nPreviousDigit = 0;

            nDigit = int.Parse(strReverseNumberText.Substring(nCurrentPosition, 1));

            if (nCurrentPosition < nMaxPosition)
                nPreviousDigit = int.Parse(strReverseNumberText.Substring(nCurrentPosition + 1, 1));
            // notice: lngPosition = (lngCurrentPosition - 1) Mod 6 + 1
            nPosition = (nCurrentPosition - 1) % 6 + 1;

            if (nDigit == 0 && nMaxPosition > 0 || nDigit == 1 && nPosition == 1)
                strDigitName = "";
            else if (nDigit == 1 && (nPosition == 0 || nPosition == 6)
                && nMaxPosition > nCurrentPosition
                && nPreviousDigit > 0)
                strDigitName = "เอ็ด";
            else if (nDigit == 2 && nPosition == 1)
                strDigitName = "ยี่";
            else
                strDigitName = astrDigitName[nDigit];

            if (nDigit == 0 && nPosition != 6)
                strPositionName = "";
            else
                strPositionName = astrPositionName[nPosition];

            return strDigitName + strPositionName;
        }

        public string MoneyTextThai(double dblNumber)
        {
            return MoneyTextThai(dblNumber.ToString(), "บาท", "สตางค์");
        }

        public string MoneyTextThai(decimal dblNumber)
        {
            return MoneyTextThai(dblNumber.ToString(), "บาท", "สตางค์");
        }

        public string MoneyTextThai(string strNumberText)
        {
            return MoneyTextThai(strNumberText, "บาท", "สตางค์");
        }

        public string MoneyTextThai(string strNumberText, string strCurrencyMain, string strCurrencyPercent)
        {
            string strResult = "";
            string[] astrPositionName = { "", "สิบ", "ร้อย", "พัน", "หมื่น", "แสน", "ล้าน" };
            string[] astrDigitName = { "ศูนย์", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า" };
            string strReverseBaht;
            string strReverseSatang;
            int nPointPosition;
            int nMaxPosition;
            int nCurrentPosition;

            // simplify the number
            strNumberText = strNumberText.Trim().Replace(",", "");

            while (strNumberText.Length > 1
                && StringX.Left(strNumberText, 1) == "0"
                && StringX.Left(strNumberText, 2) != "0.")
                strNumberText = strNumberText.Substring(1);

            // check number validation
            if (!IsAValidNumber(strNumberText))
                throw new Exception(strNumberText + " ไม่ใช่จำนวนที่ถูกต้อง");

            // separate baht and satang
            nPointPosition = strNumberText.IndexOf(".");

            if (nPointPosition >= 0)
            {
                strReverseBaht = StringX.StrReverse(strNumberText.Substring(0, nPointPosition));
                strReverseSatang
                    = StringX.StrReverse(StringX.Right(double.Parse(strNumberText.Substring(nPointPosition)).ToString(".00"), 2));
            }
            else
            {
                strReverseBaht = StringX.StrReverse(strNumberText);
                strReverseSatang = "00";
            }

            // begin process baht
            nMaxPosition = strReverseBaht.Length - 1;

            for (nCurrentPosition = nMaxPosition; nCurrentPosition >= 0; nCurrentPosition--)
            {
                strResult += EachNumberPositionThaiText(strReverseBaht
                    , nMaxPosition, nCurrentPosition, astrPositionName, astrDigitName);
            }

            if (strResult.Length > 0)
                strResult += strCurrencyMain;
            // end process baht

            // begin process satang
            if (strResult.Length > 0 && strReverseSatang == "00")
            {
                strResult += "ถ้วน";
            }
            else
            {
                if (strResult == "ศูนย์ " + strCurrencyMain)
                    strResult = "";

                nMaxPosition = strReverseSatang.Length - 1;

                for (nCurrentPosition = nMaxPosition; nCurrentPosition >= 0; nCurrentPosition--)
                    strResult += EachNumberPositionThaiText(strReverseSatang
                        , nMaxPosition, nCurrentPosition, astrPositionName, astrDigitName);

                if (strResult.Length > 0)
                    strResult += strCurrencyPercent;
            }
            // end process satang

            return strResult;
        }

        public string GenNewRefNo(string table,string prefix,int? year, int? month)
        {            
            try
            {
                year = year.HasValue ? year : DateTime.Now.Year;
                month = month.HasValue ? month : DateTime.Now.Month;

                var culture = new System.Globalization.CultureInfo("th-TH");
                var dateValue = new DateTime((int)year, (int)month, DateTime.Now.Day);
                
                int cnt = 0;
                string sql = "SELECT COUNT(*) as cnt FROM " + table + " WHERE YEAR(created_when) = " + year + " AND MONTH(created_when) = " + month;
                DataTable dt = ExecuteQuery(sql);
                DataRowCollection drc = null;
                drc = dt.Rows;
                if (drc.Count > 0)
                {
                    for (int i = 0; i < drc.Count; i++)
                    {
                        cnt = Convert.ToInt32(drc[i]["cnt"]);
                    }
                }
                string data = prefix.ToUpper() + "-" + dateValue.ToString("yyyy", culture) + dateValue.ToString("MM", culture) + "-" + (cnt + 1).ToString("0000");
                   return data;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    public class UserInfo
    {
        public string strUserID;
        public string strUserName;
        public string strEmpSeq;

        public UserInfo()
        {

        }

        public string UserID
        {
            get
            {
                return strUserID;
            }
            set
            {
                strUserID = value;
            }
        }

        public string UserName
        {
            get
            {
                return strUserName;
            }
            set
            {
                strUserName = value;
            }
        }

        public string EmpSeq
        {
            get
            {
                return strEmpSeq;
            }
            set
            {
                strEmpSeq = value;
            }
        }
    }

    public enum MDataType
	{
		String,
		DateTime,
		Int,
		Double
	}
}
